package com.angel.application.commandgateways;

import com.angel.application.commandgateways.commands.RegisterCommand;
import com.angel.domain.angeluser.aggregates.AngelUser;
import com.angel.domain.angeluser.event.AngelUserRegisterEvent;
import com.angel.domain.angeluser.factory.AngelUserFactory;
import com.angel.domain.angeluser.repositories.AngelUserRepository;
import com.angel.domain.angeluser.valueobjects.WeChatAvatarUrl;
import com.angel.domain.angeluser.valueobjects.WeChatNickName;
import com.angel.domain.angeluser.valueobjects.WeChatOpenId;
import com.angel.infrastructure.db.mapper.AngelUserWeChatInfoMapper;
import com.angel.infrastructure.db.po.UserWechatInfoPO;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;
/*
 * 更新关注微信公众号： 为了offer
 * @author parkin
 * @description
 * @date 2021/11/13
 */
@Service
public class RegisterCommandService {

    private final AngelUserRepository angelUserRepository;
    private final AngelUserWeChatInfoMapper angelUserWeChatInfoMapper;
    private final ApplicationContext applicationContext;

    public RegisterCommandService(AngelUserRepository angelUserRepository,
                                  AngelUserWeChatInfoMapper angelUserWeChatInfoMapper,
                                  ApplicationContext applicationContext) {

        this.angelUserRepository = angelUserRepository;
        this.angelUserWeChatInfoMapper = angelUserWeChatInfoMapper;
        this.applicationContext = applicationContext;
    }

    /**
     * 注册-暂定只支持
     * 微信注册
     */
    @Transactional(rollbackFor = Exception.class)
    public void register(RegisterCommand registerCommand){

        Optional<UserWechatInfoPO> userWechatInfoPO = angelUserWeChatInfoMapper.get(
                new WeChatOpenId(registerCommand.getAccount())
        );

        userWechatInfoPO.ifPresent((userWechatInfo) -> {throw new RuntimeException("The user already exists. Do not register again");});

        AngelUser angelUser = AngelUserFactory.create(
                new WeChatNickName(registerCommand.getNickName()),
                new WeChatOpenId(registerCommand.getAccount()),
                new WeChatAvatarUrl(registerCommand.getHeadImage())
        );

        // 执行注册
        AngelUserRegisterEvent angelUserRegisterEvent = angelUser.register();
        angelUserRepository.save(angelUser);
        // 发送注册事件
        applicationContext.publishEvent(angelUserRegisterEvent);
    }

}
